import React,{Component} from 'react';
import { message, Button,Select ,Card,Input,Form,Col,Row,Radio,Upload,Icon,Steps} from 'antd';
import { connect } from 'react-redux';
import {getUserIn,userRecruit,getRecruit} from '../../store/action/recruit';
import configs from '../../store/action/common/configs';
import reqwest from 'reqwest';
import './Recruit.css'
import { Link } from 'react-router-dom';
import {getTokenHeader} from '../../utils/utils'
const FormItem=Form.Item;
const { Step } = Steps;
const { Option } = Select;
const { TextArea } = Input;
const baseUrl=configs.baseUrl;

@connect((state)=>({
    userIn:state.recruitList.userIn,
    resumeId:state.recruit.resumeId,
    classes:state.recruit.classes
}))
class Recruit extends Component{
    constructor(props)
    {
        super(props);
        this.state={
            loading:false,
            stid:0,
            username:'',
            email:'',
            studentId:'',
            studentClass:'',
            avatar:'',
            phoneNumber:'',
            current: 0,
            step0:'process',
            step1:'wait',
            uploadingP: false,
            fileList: [],
            resumeId:5,
            classes:[],
            isLogin:true

        }
    }
    componentDidMount(){
        let _id=this.props.match.params.id;
        let roleId=window.localStorage.getItem('roleId');
        if(roleId==='3')
        {
            this.setState({
                isLogin:false
            })
        }else{
            this.setState({
                isLogin:true
            });
            this.props.dispatch(getRecruit({id:_id})).then(()=>{
                this.setState({
                    classes:this.props.classes
                })
            })
            this.props.dispatch(getUserIn({},_id)).then(()=>{
                if(this.props.userIn)
                {
                    this.setState({
                        stid:this.props.userIn.pagingList[0].id,
                        realName:this.props.userIn.pagingList[0].realName,
                        email:this.props.userIn.pagingList[0].email,
                        studentId:this.props.userIn.pagingList[0].studentId,
                        studentClass:this.props.userIn.pagingList[0].studentClass,
                        institution:this.props.userIn.pagingList[0].institution,
                        avatar:this.props.userIn.pagingList[0].avatar,
                        phoneNumber:this.props.userIn.pagingList[0].phoneNumber,
                    })
                }
                
            });
            
        }
       
        
    }
    /**
     * 图片调用
     */
    getBase64 = (img, callback) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }
    beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('请上传jpg或png格式的照片');
        }
        const isLt2M = file.size / 100 / 1024 < 3;
        if (!isLt2M) {
            message.error('请上传小于300kb的照片!');
        }
        return isJpgOrPng && isLt2M;
    }
   
    handleChange = info => {
        if (info.file.status === 'uploading') {
            this.setState({
                loading: true
            });
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            this.getBase64(info.file.originFileObj, imageUrl => {
                    if (info.file.response.code === 'SUCCESS') {
                        this.setState({
                            imageUrl,
                            loading: false,
                            avatar: info.file.response.data.url
                        });
                    } else {
                        this.setState({
                            loading: false
                        })
                        if(info.file.response.msg==='Jwt expired')
                        {
                            message.error("头像上传失败：" + info.file.response.msg);
                        }else{
                            message.error("头像上传失败");
                        }
                        
                    }
                }

            );
        }

    };

      onStepChange = current => {
        this.setState({ current:current });
      };
      /**
       * 提交基本内容表单
       */
      handleSubmitForm=()=>{
          let data = this.props.form.getFieldsValue();
          let formData={};
          let _id=this.props.match.params.id;
          //判断是否有为空的
          if(!data.name||
            !data.sex||
            !data.stuNum||
            this.state.avatar.indexOf("http")===-1||
            !data.institution||
            !data.email||
            !data.majorClass||
            !data.phone||
            !parseInt(data.mathScore)||
            !parseInt(data.englishScore)||
            !data.willingClass||
            !data.applyReason||
            !data.prizeExperiencen)
            {

                message.error("请将带红色‘*’的内容填写完整");
            }
            else{
            formData.enrollId=parseInt(_id);
            formData.name=data.name;
            formData.sex=data.sex;
            formData.stuNum=data.stuNum;
            formData.avatar=this.state.avatar;
            formData.institution=data.institution;
            formData.email=data.email;
            formData.majorClass=data.majorClass;
            formData.phone=data.phone;
            formData.mathScore=parseInt(data.mathScore);
            formData.englishScore=parseInt(data.englishScore);
            formData.patScore=data.patScore;
            formData.ccfScore=parseInt(data.ccfScore);
            formData.willingClass=data.willingClass;
            formData.applyReason=data.applyReason;
            formData.prizeExperience=data.prizeExperiencen;
           

            this.props.dispatch(userRecruit(formData)).then(()=>{
               
                    this.setState({
                        resumeId:this.props.resumeId
                      });
                      setTimeout(()=>{
                        this.setState({
                            current:1,
                            step0:'wait',
                            step1:'process',
                        })
                      },1000)
                
            });
            }
      }
      handleUpload = () => {
        const { fileList} = this.state;
        const formData = new FormData();
        this.setState({
            uploading: true,
          });
          let flag=0;
        fileList.forEach(file => {
            const isLt2M = file.size / 100 / 1024 < 3;
            if (!isLt2M) {
                message.error('请上传小于300kb的文件!');
            }
            else{
                formData.append('file', file);
                formData.append('resumeId',this.props.resumeId);
                let headers=getTokenHeader({});
                reqwest({
                  url: `${baseUrl}file/prizeFile.do`,
                  method: 'post',
                  processData: false,
                  data: formData,
                  headers:headers,
                  success: (data) => {
                     message.success('上传成功.');
                  },
                  error: () => {
                    this.setState({
                      uploading: false,
                    });
                    flag=1;
                    message.error('上传失败.');
                  },
                });
            }
          
        });

        this.setState({
            fileList: [],
            uploading: false,
          });
    
        // You can use any AJAX library you like
       
      };
    render(){
        const {getFieldDecorator}=this.props.form;
        const { imageUrl,current,uploading, fileList } = this.state;
        const stepStyle = {
            marginBottom: 60,
            boxShadow: '0px -1px 0 0 #e8e8e8 inset',
          };
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">请上传jpg或png格式并小于300kb的个人照片</div>
            </div>
        );
        const props = {
            onRemove: file => {
              this.setState(state => {
                const index = state.fileList.indexOf(file);
                const newFileList = state.fileList.slice();
                newFileList.splice(index, 1);
                return {
                  fileList: newFileList,
                };
              });
            },
            beforeUpload: file => {
              this.setState(state => ({
                fileList: [...state.fileList, file],
              }));
              return false;
            },
            fileList,
          };
      
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        
          
        return(
            <div>
                {
                    this.state.isLogin? <Card bordered={false}>
                    <div>
                    <Steps
                        type="navigation"
                        size="small"
                        current={current}
                        style={stepStyle}
                        >
                        <Step status={this.state.step0} title="基本信息" />
                        <Step status={this.state.step1} title="提交附件" />
                    </Steps>
                    </div>
                    {
                        this.state.current===0? <Form layout='horizontal'>
                        <Row>
                            <Col span={9}>
                            <FormItem label="姓名" {...formItemLayout}>
                                {
                                    getFieldDecorator('name',{
                                        initialValue:this.state.realName,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请填写您的姓名',
                                            },
                                            {
                                                min: 2,
                                                message: '姓名至少为 2 个字符',
                                            },
                                            {
                                                max: 20,
                                                message: '姓名至多为 15 个字符',
                                            },]
                                    })(<Input />)
                                }
                            </FormItem>
                        <FormItem label="学号" {...formItemLayout}>
                            {
                                getFieldDecorator('stuNum',{
                                    initialValue:this.state.studentId,
                                    rules:[{
                                        required: true,
                                        message: '请填写您的学号',
                                    }]
                                })(<Input />)
                            }
                        </FormItem>
                        <FormItem label="性别" {...formItemLayout}>
                            {
                                getFieldDecorator('sex',{
                                    initialValue:1,
                                    rules:[{
                                        required: true,
                                        message: '请选择您的性别',
                                    }]
                                })(<Radio.Group>
                                    <Radio value={1}>男</Radio>
                                    <Radio value={2}>女</Radio>
                                </Radio.Group>)
                            }
                        </FormItem>
                        <FormItem label="邮箱" {...formItemLayout}>
                            {
                                getFieldDecorator('email',{
                                    initialValue:this.state.email,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请填写您的邮箱',
                                        },
                                        {
                                            pattern: '^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$',
                                            message: '请输入正确格式的邮箱号',
                                        },]
                                })(<Input />)
                            }
                        </FormItem>
                        </Col>
                        <Col span={9}>
                        <FormItem label="手机号码" {...formItemLayout}>
                            {
                                getFieldDecorator('phone',{
                                    initialValue:this.state.phoneNumber,
                                    rules:[{
                                        required: true,
                                        message: '请填写您的手机号',
                                    }, {
                                        pattern: '^[1][3|4|5|6|7|8|9][0-9]{9}$',
                                        message: '请输入正确的手机号格式。',
                                    },]
                                })(<Input />)
                            }
                        </FormItem>
                        <FormItem label="班级" {...formItemLayout}>
                                {
                                    getFieldDecorator('majorClass',{
                                        initialValue:this.state.studentClass,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请填写您的班级',
                                            }]
                                    })(<Input />)
                                }
                            </FormItem>
                        <FormItem label="学院" {...formItemLayout}>
                            {
                                getFieldDecorator('institution',{
                                    initialValue:this.state.institution,
                                    rules:[{
                                        required: true,
                                        message: '请选择您的学院',
                                    }]

                                })(<Select >
                                <Option value="计算机科学与技术学院">计算机科学与技术学院</Option>
                                <Option value="材料科学与工程学院">材料科学与工程学院</Option>
                                <Option value="土木工程与建筑学院">土木工程与建筑学院</Option>
                                <Option value="信息工程学院">信息工程学院</Option>
                                <Option value="理学院">理学院</Option>
                                <Option value="法学院">法学院</Option>
                                <Option value="外国语学院">外国语学院</Option>
                                <Option value="体育学科部">体育学科部</Option>
                                <Option value="环境与资源学院">环境与资源学院</Option>
                                <Option value="制造科学与工程学院">制造科学与工程学院</Option>
                                <Option value="生命科学与工程/农学院">生命科学与工程/农学院</Option>
                                <Option value="国防科技学院">国防科技学院</Option>
                                <Option value="经济管理学院">经济管理学院</Option>
                                <Option value="文学与艺术学院">文学与艺术学院</Option>
                                <Option value="马克思主义学院">马克思主义学院</Option>
                                <Option value="应用技术学院">应用技术学院</Option>

                            </Select>)
                            }
                        </FormItem>
                        <FormItem label="志愿班级" {...formItemLayout}>
                            {
                                getFieldDecorator('willingClass',{
                                    rules:[{
                                        required: true,
                                        message: '请选择您志愿的班级',
                                    }]
                                })(<Select style={{ width: 120 }}>
                                {
                                    this.state.classes.map((item,index)=>{
                                    return <Option key={index} value={item}>{item}</Option>
                                    })
                                }
                              </Select>)
                            }
                        </FormItem>
                        </Col>
                        <Col span={6}>
                        <FormItem label="照片" >
                            {getFieldDecorator('avatar', {
                                initialValue:'',
                                rules:[{
                                    required: true,
                                    message: '请上传头像',
                                }]
                            })(
                                <Upload
                                    name="file"
                                    listType="picture-card"
                                    className="avatar-uploader"
                                    showUploadList={false}
                                    action={`${baseUrl}file/avatar.do`}
                                    headers={getTokenHeader({})}
                                    onChange={this.handleChange}
                                    beforeUpload={this.beforeUpload}
                                >
                                    {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                                </Upload>
                            )}
                        </FormItem>
                        </Col>
                        </Row>
                        <Row >
                            <Col span={6}>
                            <FormItem label="第一学期高数成绩：">
                            {
                                getFieldDecorator('mathScore',{
                                    initialValue:'',
                                    rules:[{
                                        required: true,
                                        message: '请填写您第一学期高数成绩',
                                    },
                                    {
                                        pattern: '^(0|[1-9][0-9]?|100)$',
                                        message: '请输入0~100整数。',
                                    },]
                                })(<Input style={{ width: 120 }} />)
                            }
                        </FormItem>
                            </Col>
                            <Col span={6}>
                            <FormItem label="第一学期英语分数：">
                            {
                                getFieldDecorator('englishScore',{
                                    initialValue:'',
                                    rules:[{
                                        required: true,
                                        message: '请填写您第一学期英语分数',
                                    }, {
                                        pattern: '^(0|[1-9][0-9]?|100)$',
                                        message: '请输入0~100整数。',
                                    },]
                                })(<Input style={{ width: 120 }} />)
                            }
                        </FormItem>
                            </Col>
                            <Col span={6}>
                            <FormItem label="PAT成绩(例如：甲级70分 or 乙级70分)：">
                            {
                                getFieldDecorator('patScore',{
                                    initialValue:'',
                                })(<Input style={{ width: 120 }} />)
                            }
                        </FormItem>
                            </Col>
                            <Col span={5}>
                            <FormItem label="CSP成绩：">
                            {
                                getFieldDecorator('ccfScore',{
                                    initialValue:'',
                                    rules:[{
                                        pattern: '^[0-9]*$',
                                        message: '请输入整数。',
                                    },]
                                })(<Input style={{ width: 120 }} />)
                            }
                        </FormItem>
                            </Col>
                        </Row>
                        <Row>
                        
                        <FormItem label="申请原因：" >
                            {
                                getFieldDecorator('applyReason',{
                                    initialValue:'',
                                    rules:[{
                                        required: true,
                                        message: '请填写您的申请原因',
                                    }]
                                })( <TextArea placeholder="" style={{width:'50vw'}}  autoSize={{ minRows: 2, maxRows: 6 }} /> )
                            }
                        </FormItem>
                        <FormItem label="获奖经历：" >
                            {
                                getFieldDecorator('prizeExperiencen',{
                                    initialValue:'',
                                    rules:[{
                                        required: true,
                                        message: '请填写您的获奖经历',
                                    }]
                                })( <TextArea placeholder="请填写高中以上的获奖经历，并分点列出,如果没有请填无" style={{width:'50vw'}} autoSize={{ minRows: 2, maxRows: 6 }} /> )
                            }
                        </FormItem>
                        </Row>
                        <Button onClick={this.handleSubmitForm}>提交</Button>
                    </Form>:<><div className="upload">
                        <div>上传附件(文件大小不超过300kb)：</div>
                        <br></br>
                             <Upload {...props}>
          <Button>
            <Icon type="upload" />选择文件
          </Button>
        </Upload>
        <Button
          type="primary"
          onClick={this.handleUpload}
          disabled={fileList.length === 0}
          loading={uploading}
          style={{ marginTop: 16 }}
        >
          {uploading ? '上传中' : '开始上传'}
        </Button>
       
                    </div>
                     <div className='recruit-finish'>
                     <Link to={'/enroll'}> <Button type='primary'>完成</Button></Link>
                 </div></>
                    }
                </Card>:<div>
                    <div className="no-login">
                        您未登录或token已过期，请在<a href="http://acm.swust.edu.cn/dev/">oj登录</a>后再通过链接回到本网站。
                    </div>
                </div>
                }
                
            </div>
        )
    }
}
export default Form.create()(Recruit);